package com.example.springsecuritydemo2.config;

import com.alibaba.fastjson.JSON;
import com.example.springsecuritydemo2.common.R;
import com.example.springsecuritydemo2.filter.JwtAuthenticationTokenFilter;
import com.example.springsecuritydemo2.handler.AnonymousAuthenticationHandler;
import com.example.springsecuritydemo2.handler.CustomerAccessDeniedHandler;
import com.example.springsecuritydemo2.handler.LoginFailureHandler;
import jakarta.servlet.ServletOutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.WebSecurityConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.nio.charset.StandardCharsets;

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

    // 自定义用于认证的过滤器，进行jwt的校验操作
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private CustomerAccessDeniedHandler customerAccessDeniedHandler;

    @Autowired
    private AnonymousAuthenticationHandler anonymousAuthenticationHandler;

    @Autowired
    private LoginFailureHandler loginFailureHandler;

    /**
     * 密码编码器
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 认证管理器
     *
     * @param config
     * @return
     * @throws Exception
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception {
        return config.getAuthenticationManager();
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        // 禁用csrf
        http.csrf(AbstractHttpConfigurer::disable);


        // 用户认证校验失败处理器
        http.formLogin(form -> form.failureHandler(loginFailureHandler));


        http.authorizeHttpRequests(auth -> auth.requestMatchers("/user/login")
                .permitAll()
                .anyRequest()
                .authenticated());
        // 配置过滤器的执行顺序
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // 配置异常处理器
        http.exceptionHandling(exception ->
                exception.accessDeniedHandler(customerAccessDeniedHandler)
                        .authenticationEntryPoint(anonymousAuthenticationHandler)
        );
        return http.build();
    }
}